package 第二周;

/**
 * @author xhw
 */

public class 整数反转 {

    public static void main(String[] args) {
        int test1 = 123;
        int test2 = -123;
        int test3 = 120;
        int test4 = 0;
        System.out.println(reverse(test1));
        System.out.println(reverse(test2));
        System.out.println(reverse(test3));
        System.out.println(reverse(test4));
    }

    public static int reverse(int x) {
        int rev = 0;

        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }

        return rev;
    }
}